<template>
  <div>
    <!-- #region Add User -->

    <!-- #endregion -->

    <el-button type="primary" @click="addRole">添加角色</el-button>
    <!-- #region Dialog -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="70%">
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRoles"
        label-width="80px"
        status-icon
      >
        <el-form-item label="角色名" prop="name">
          <xy-input v-model="addForm.name" clearable></xy-input>
        </el-form-item>
        <el-form-item label="权限" prop="menus">
          <!-- <el-transfer
            v-model="addForm.menus"
            :titles="titles"
            :props="{
              key: 'menuId',
              label: 'name',
            }"
            :data="menus"
          ></el-transfer> -->
          <el-cascader
            ref="cascaderRef"
            @change="menusChange"
            :options="menus"
            v-model="addForm.buttons"
            :props="props"
            clearable
            size="mini"
          >
            <template slot-scope="{ node, data }">
              <span>{{ data.name || data.method }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('addFormRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- #endregion -->
  </div>
</template>

<script>
export default {
  data() {
    const validateName = (rule, value, callback) => {
      if (/^[\u4e00-\u9fa5\w]+$/.test(value)) {
        callback();
      } else {
        callback(new Error("输入了无效字符"));
      }
    };
    const validateButtons = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error("请选择权限"));
      } else {
        callback();
      }
    };

    return {
      props: {
        multiple: true,
        label: "name",
        value: "id",
        expandTrigger: "hover",
        emitPath: false,
        checkStrictly: false,
      },
      selectMenus: [],
      menus: null,
      buttons: [],
      addDialogVisible: false,
      addForm: {
        name: "",
        buttons: [],
      },
      addFormRoles: {
        name: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 2,
            message: "长度在 不小于 2 个字符",
            trigger: "blur",
          },
          {
            max: 15,
            message: "长度在 不大于 15 个字符",
            trigger: "blur",
          },
          { validator: validateName, trigger: "blur" },
        ],
        buttons: [{ validator: validateButtons, trigger: "blur" }],
      },
    };
  },
  created() {},
  methods: {
    addRole() {
      this.addDialogVisible = true;
      console.log(this.$store.getters.data);
      let { menus } = this.$store.getters.data;
      // console.log(menus);
      this.menus = menus;
      for (const menu of this.menus) {
        menu.children = menu.subMenus || undefined;
        for (const subMenu of menu.children) {
          if (subMenu.buttons && subMenu.buttons.length > 0) {
            subMenu.children = subMenu.buttons;
            this.buttons = this.buttons.concat(subMenu.buttons);
          } else {
            subMenu.children = undefined;
          }
        }
      }
    },
    // handleClose() {
    //   this.$confirm("确认关闭？")
    //     .then(() => {
    //       // done();
    //       this.addDialogVisible = false;
    //     })
    //     .catch(() => {});
    // },
    menusChange(item) {
      console.log(item);
    },

    onSubmit(formName) {
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }
        try {
          console.log(this.addForm);
          //  this.$emit("addRole", this.addForm);

          // for (const key in this.addFrom) {
          //   if (Object.hasOwnProperty.call(this.addForm, key)) {
          //     this.addForm[key] = "";
          //   }
          // }
          console.log(this.buttons);

          let buttons = [];
          for (const menu of this.menus) {
            if (menu.subMenus) {
              for (const subMenu of menu.subMenus) {
                if (subMenu.buttons) {
                  for (const button of subMenu.buttons) {
                    // console.log(button.id);
                    if (
                      this.addForm.buttons.findIndex((v) => v === button.id) !=
                      -1
                    ) {
                      buttons.push(button);
                    }
                  }
                }
              }
            }
          }
          console.log(buttons);
          console.log(this.addForm);
          let response = await this.$http.post("/api/Roles", this.addForm);
          console.log(response);
        } catch (error) {
          console.error(error);
        } finally {
          this.addDialogVisible = false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>
